<template>
  <div class="messages-container">
    <!-- 搜索表单 -->
    <a-form
      layout="inline"
      :model="searchForm"
      @finish="handleSearch"
      class="search-form"
    >
      <a-form-item label="机器码" name="robotId">
        <a-select
          v-model:value="searchForm.robotId"
          allowClear
          placeholder="请选择机器码"
          style="width: 200px"
        >
          <a-select-option
            v-for="robot in robots"
            :key="robot.robotId"
            :value="robot.robotId"
          >
            {{ robot.robotId }}
          </a-select-option>
        </a-select>
      </a-form-item>

      <a-form-item label="消息类型" name="type">
        <a-select
          v-model:value="searchForm.type"
          allowClear
          placeholder="请选择消息类型"
          style="width: 150px"
        >
          <a-select-option
            v-for="type in messageTypes"
            :key="type.value"
            :value="type.value"
          >
            {{ type.label }}
          </a-select-option>
        </a-select>
      </a-form-item>

      <a-form-item label="时间范围">
        <a-range-picker
          v-model:value="searchForm.dateRange"
          :show-time="{ format: 'HH:mm' }"
          format="YYYY-MM-DD HH:mm"
          :placeholder="['开始时间', '结束时间']"
        />
      </a-form-item>

      <a-form-item>
        <a-space>
          <a-button type="primary" html-type="submit">
            <search-outlined /> 搜索
          </a-button>
          <a-button @click="handleReset">
            <reload-outlined /> 重置
          </a-button>
        </a-space>
      </a-form-item>
    </a-form>

    <!-- 消息列表 -->
    <a-table
      :columns="columns"
      :data-source="messages"
      :loading="loading"
      :pagination="pagination"
      @change="handleTableChange"
    >
      <template #type="{ text }">
        <a-tag>{{ getMessageTypeName(text) }}</a-tag>
      </template>

      <template #status="{ text }">
        <a-tag :color="text === 1 ? 'success' : 'error'">
          {{ text === 1 ? '成功' : '失败' }}
        </a-tag>
      </template>

      <template #action="{ record }">
        <a-space>
          <a @click="handleViewDetail(record)">查看</a>
          <a-divider type="vertical" />
          <a
            v-if="record.status !== 1"
            @click="handleResend(record)"
          >重发</a>
        </a-space>
      </template>
    </a-table>

    <!-- 消息详情弹窗 -->
    <a-modal
      v-model:visible="detailVisible"
      title="消息详情"
      width="800px"
      :footer="null"
    >
      <a-descriptions bordered :column="1">
        <a-descriptions-item label="机器码">
          {{ currentMessage?.robotId }}
        </a-descriptions-item>
        <a-descriptions-item label="消息类型">
          {{ getMessageTypeName(currentMessage?.type) }}
        </a-descriptions-item>
        <a-descriptions-item label="消息内容">
          <pre class="message-content">{{ formatContent(currentMessage?.content) }}</pre>
        </a-descriptions-item>
        <a-descriptions-item label="状态">
          <a-tag :color="currentMessage?.status === 1 ? 'success' : 'error'">
            {{ currentMessage?.status === 1 ? '成功' : '失败' }}
          </a-tag>
        </a-descriptions-item>
        <a-descriptions-item label="创建时间">
          {{ currentMessage?.createTime }}
        </a-descriptions-item>
        <a-descriptions-item label="更新时间">
          {{ currentMessage?.updateTime }}
        </a-descriptions-item>
      </a-descriptions>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import { SearchOutlined, ReloadOutlined } from '@ant-design/icons-vue'
import { getMessages, getMessageTypes, resendMessage } from '@/api/message'
import { getRobotCodes } from '@/api/robot'

// 搜索表单
const searchForm = reactive({
  robotId: undefined,
  type: undefined,
  dateRange: []
})

// 列表相关
const loading = ref(false)
const messages = ref([])
const robots = ref([])
const messageTypes = ref([])
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showTotal: total => `共 ${total} 条`
})

const columns = [
  {
    title: 'ID',
    dataIndex: 'id',
    width: 80
  },
  {
    title: '机器码',
    dataIndex: 'robotId',
    width: 200
  },
  {
    title: '类型',
    dataIndex: 'type',
    width: 100,
    slots: { customRender: 'type' }
  },
  {
    title: '内容',
    dataIndex: 'content',
    ellipsis: true
  },
  {
    title: '状态',
    dataIndex: 'status',
    width: 100,
    slots: { customRender: 'status' }
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    width: 180
  },
  {
    title: '操作',
    key: 'action',
    width: 150,
    slots: { customRender: 'action' }
  }
]

// 详情弹��
const detailVisible = ref(false)
const currentMessage = ref(null)

// 获取消息列表
const fetchMessages = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.current,
      pageSize: pagination.pageSize,
      robotId: searchForm.robotId,
      type: searchForm.type,
      startTime: searchForm.dateRange[0]?.format('YYYY-MM-DD HH:mm:ss'),
      endTime: searchForm.dateRange[1]?.format('YYYY-MM-DD HH:mm:ss')
    }
    const { data } = await getMessages(params)
    messages.value = data.list
    pagination.total = data.total
  } catch (error) {
    console.error('获取消息列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 获取机器码列表
const fetchRobots = async () => {
  try {
    const { data } = await getRobotCodes({ pageSize: 1000 })
    robots.value = data.list
  } catch (error) {
    console.error('获取机器码列表失败:', error)
  }
}

// 获取消息类型列表
const fetchMessageTypes = async () => {
  try {
    const { data } = await getMessageTypes()
    messageTypes.value = data
  } catch (error) {
    console.error('获取消息类型列表失败:', error)
  }
}

// 获取消息类型名称
const getMessageTypeName = (type) => {
  const found = messageTypes.value.find(t => t.value === type)
  return found ? found.label : type
}

// 格式化消息内容
const formatContent = (content) => {
  try {
    return typeof content === 'string' ? content : JSON.stringify(content, null, 2)
  } catch (error) {
    return content
  }
}

// 表格变化处理
const handleTableChange = (pag) => {
  pagination.current = pag.current
  pagination.pageSize = pag.pageSize
  fetchMessages()
}

// 搜索处理
const handleSearch = () => {
  pagination.current = 1
  fetchMessages()
}

// 重置搜索
const handleReset = () => {
  searchForm.robotId = undefined
  searchForm.type = undefined
  searchForm.dateRange = []
  handleSearch()
}

// 查看详情
const handleViewDetail = (record) => {
  currentMessage.value = record
  detailVisible.value = true
}

// 重发消息
const handleResend = async (record) => {
  try {
    await resendMessage(record.id)
    message.success('重发成功')
    fetchMessages()
  } catch (error) {
    console.error('重发消息失败:', error)
  }
}

onMounted(() => {
  fetchRobots()
  fetchMessageTypes()
  fetchMessages()
})
</script>

<style scoped>
.messages-container {
  padding: 24px;
  background: #fff;
}

.search-form {
  margin-bottom: 24px;
}

.message-content {
  margin: 0;
  white-space: pre-wrap;
  word-wrap: break-word;
  max-height: 300px;
  overflow-y: auto;
}
</style> 